package com.huanyang.exception;

import com.huanyang.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object exceptionHandler(HttpServletRequest request, Exception e) {
        LOGGER.error("【统一异常拦截】请求地址：{}, 错误信息：{}", request.getRequestURI(), e.getMessage());
        // 注解验证抛出异常
        if (e instanceof MethodArgumentNotValidException) {
            // 获取错误信息
            String error = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
            return Result.fail(500, error);
        }
        // 自定义异常
        if (e instanceof CommonException) {
            return Result.fail(((CommonException) e).getCode(),e.getMessage());
        }
        return Result.fail(999, e.getMessage());
    }
}
